package com.medisign.sign.log.util;

import com.medisign.sign.log.config.SystemConfig;
import com.medisign.sign.log.pojo.TbSignLog;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.sql.*;

@Slf4j
@RequiredArgsConstructor
@Component
public class BaseDataSourceUtil {

    private final SystemConfig systemConfig;

    private Connection getBaseDataSourceConnection() {
        SystemConfig.DataSourceInfo dataSourceInfo = systemConfig.getDataSourceInfo();
        Connection con;
        String driverName= dataSourceInfo.getDriverClassName();
        String dbURL= dataSourceInfo.getUrl();
        String userName= dataSourceInfo.getUsername();
        String userPwd= dataSourceInfo.getPassword();
        try {
            Class.forName(driverName); //jdk版本6.0以上可以省略这句话
            con= DriverManager.getConnection(dbURL,userName,userPwd);
            return con;
        }catch(Exception e) {
            log.error("获取baseDataSouurce连接失败,错误信息为:{}", e);
            throw new RuntimeException("获取mysql连接失败!");
        }
    }

    private void closeConnection(Connection con, Statement st, ResultSet rs) {
        if (null != rs) {
            try {
                rs.close();
            } catch (SQLException e) {
                log.error("关闭ResultSet失败,{}", e);
            }
        }
        if (null != st) {
            try {
                st.close();
            } catch (SQLException e) {
                log.error("关闭Statement失败,{}", e);
            }
        }
        if (null != con) {
            try {
                con.close();
            } catch (SQLException e) {
                log.error("关闭Connection失败,{}", e);
            }
        }
    }

    public void save(TbSignLog signLog) {
        Connection connection = getBaseDataSourceConnection();
        PreparedStatement pstmt = null;
        try {
            pstmt = connection.prepareStatement("INSERT INTO tb_sign_log (file_code, start_time, end_time, unsign_data, signed_data, timestamp,sign_cert, log_path, strategy) VALUES (?,?,?,?,?,?,?,?,?)");
            pstmt.setString(1, signLog.getFileCode());
            pstmt.setTimestamp(2, new Timestamp(signLog.getStartTime().getTime()));
            pstmt.setTimestamp(3, new Timestamp(signLog.getEndTime().getTime()));
            pstmt.setString(4, signLog.getUnsignData());
            pstmt.setString(5, signLog.getSignedData());
            pstmt.setString(6, signLog.getTimestamp());
            pstmt.setString(7, signLog.getSignCert());
            pstmt.setString(8, signLog.getLogPath());
            pstmt.setString(9, signLog.getStrategy());
            pstmt.executeUpdate();
        } catch (SQLException e) {
            log.error("{}", e);
        }finally {
            closeConnection(connection, pstmt, null);
        }

    }

}
